package edu.uit.se.slgroup.construct.dao;

import java.io.Serializable;
import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import edu.uit.se.slgroup.construct.domain.Category;

public class CategoryDaoImpl implements CategoryDao{
	
	@Autowired
	SessionFactory sessionFactory;
	
	@Transactional
	public int insertCategory(Category category) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(category);
		tx.commit();
		Serializable id = session.getIdentifier(category);
		session.close();
		return (Integer) id;
	}

	public List<Category> getCategoryList() {
		Session session = sessionFactory.openSession();
		@SuppressWarnings("unchecked")
		List<Category> categoryList = session.createQuery("from Category").list();
		session.close();
		return categoryList;
	}

	public Category getCategoryById(int id) {
		Session session = sessionFactory.openSession();
		Category category = (Category) session.load(Category.class, id);
		//dong ket noi, nhieu truong hop khong lay duoc obj
		//session.close();
		return category;
	}

	public int updateCategory(Category category) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(category);
		tx.commit();
		Serializable id = session.getIdentifier(category);
		session.close();
		return (Integer) id;
	}

	public int deleteCategory(int id) {
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		Category category = (Category) session.load(Category.class, id);
		session.delete(category);
		tx.commit();
		Serializable ids = session.getIdentifier(category);
		session.close();
		return (Integer) ids;
	}

}
